package org.example.trigger.job;

import com.alibaba.fastjson.JSON;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.user_raffle.model.entity.StockZeroTaskEntity;
import org.example.domain.user_raffle.model.event.message.StockZeroMessage;
import org.example.domain.user_raffle.service.IUserRaffleService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author lxc18
 * @date 2025/4/2 12:16
 * @description StockZeroTask
 */
@Slf4j
@Component
public class StockZeroTask {

    //
    @Resource
    @Qualifier("threadPoolExecutor")
    private ThreadPoolExecutor executor;
    @Resource
    private IUserRaffleService userRaffleService;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @XxlJob("StockZeroTask")
    public void stockZeroTask() {
        log.info("库存清零MQ消息任务失败补偿执行");
        //TODO：扫描数据库，将失败状态的task重新发送，不需要更新状态，消费成功后自然会更新状态
        //获取所有失败的task
        List<StockZeroTaskEntity> allFailedTaskIds = userRaffleService.getAllFailedTaskIds();
        if (allFailedTaskIds != null && allFailedTaskIds.size() > 0) {
            allFailedTaskIds.forEach(stockZeroTaskEntity -> {
                //重新发送
                executor.submit(() -> {
                    try {
                        log.info("库存清零MQ消息任务失败补偿执行，prizeId:{}", stockZeroTaskEntity.getPrizeId());
                        StockZeroMessage message = new StockZeroMessage(stockZeroTaskEntity.getId(), stockZeroTaskEntity.getPrizeId());
                        String JSONString = JSON.toJSONString(message);
                        rabbitTemplate.convertAndSend("stock-zero-exchange","stock.zero",JSONString);
                    }
                    catch (Exception e) {
                        log.error("库存清零MQ消息任务失败补偿执行失败", e);
                    }
                });
            });
        }
    }
}
